package org.vaadinpa.logic.commands;

import org.vaadinpa.Conf;
import org.vaadinpa.data.NewsItem;
import org.vaadinpa.data.Planet;
import org.vaadinpa.data.Resource;
import org.vaadinpa.exceptions.NotEnoughFundsException;
import org.vaadinpa.logic.Command;
import org.vaadinpa.logic.CommandHandler;

public class TechAdvanceCommand extends Command implements Cloneable {

	public final int eta;
	public int traveled = 0;

	public TechAdvanceCommand(Planet from) throws NotEnoughFundsException {
		super(from);

		eta = Conf.ETA_LEVEL_UP_LEVEL[planet.level.ordinal()];

		// withdraw resources
		int metal = planet.level.costToNext(Resource.METAL);
		int crystal = planet.level.costToNext(Resource.CRYSTAL);
		int gold = planet.level.costToNext(Resource.GOLD);
		planet.withdrawFunds(metal, crystal, gold);
	}

	@Override
	public void execute() {

		traveled++;
		if (traveled != eta) {
			// not done yet
			TechAdvanceCommand clone = (TechAdvanceCommand) clone();
			CommandHandler.handle(clone);

		} else {
			// advance one step
			planet.levelUp();

			NewsItem i = new NewsItem("Planet Level Up complete", "New Tech Level is " + (planet.level.ordinal() + 1));
			planet.addNews(i);
		}
	}

	@Override
	public Object clone() {
		try {
			return super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void cancel() {
		double returnRate = traveled == 0 ? 1.0 : Conf.REFUND_TECH_LEVEL_UP;

		// return funds
		int metal = (int) (planet.level.costToNext(Resource.METAL) * returnRate);
		int crystal = (int) (planet.level.costToNext(Resource.CRYSTAL) * returnRate);
		int gold = (int) (planet.level.costToNext(Resource.GOLD) * returnRate);
		planet.depositFunds(metal, crystal, gold);

		NewsItem i = new NewsItem("Level up canceled", "Level Up was canceled, funds have been returned");
		planet.addNews(i);

	}

	@Override
	public String getDescription() {
		return "Advancing to level " + (planet.level.ordinal() + 2) + ", ETA " + (eta - traveled) + " ticks";
	}

	@Override
	public String getName() {
		return "Advancing";
	}

	@Override
	public void serialize(StringBuilder sb) {
		super.serializeBase(sb);

		sb.append("<eta>" + eta + "</eta>");
		sb.append("<traveled>" + traveled + "</traveled>");
		sb.append("</" + this.getClass().getSimpleName() + ">");
	}

}
